package main;

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import java.util.regex.Pattern;

public class AddressBook {
    private javax.swing.JPanel JPanel;
    private JTextField textField1; //姓名
    private JTextField textField2; //
    private JTextField textField3;
    private JTextField textField4;
    private JTextField textField5;
    private JButton Button1; //创建
    private JButton Button2; //修改
    private JButton Button3; //保存
    private JButton Button4; //删除
    private JButton Button5; //退出
    private JList list1;

    // 创建Person对象
    public Person newPerson(String n, String s, String p, String e, String m) {
        Person pp = new Person();
        pp.Setter(n, s, p, e, m);
        return pp;
    }

    // 序列化
    public void save(Hashtable<String, Person> ht) {
        ObjectOutputStream oos = null;
        try {
            //创建序列化流对象
            oos = new ObjectOutputStream(new FileOutputStream("D:\\address.ini"));
            oos.writeObject(ht);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (oos != null)
                    oos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    // 反序列化
    public Hashtable load(int n) {
        ObjectInputStream oos = null;
        Hashtable<String, Person> ht = new Hashtable<String, Person>();
        try {
            //创建序列化流对象
            oos = new ObjectInputStream(new FileInputStream("D:\\address.ini"));
            Object obj = oos.readObject();

            ht = (Hashtable<String, Person>) obj;

            ArrayList list = new ArrayList();

            //利用循环遍历出key和value
            Iterator<String> itr = ht.keySet().iterator();
            while (itr.hasNext()){
                String key = itr.next();
                list.add(key);
            }
            list1.setListData(list.toArray());
            setInfo(ht.get(list.get(0)));
            list1.setSelectedIndex(n);

            return ht;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                if (oos != null)
                    oos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return ht;
    }

    //将文本框中的值设置到 Person对象中
    public Person getInfo() {
        String name = textField1.getText();
        String birthDate = textField2.getText();
        String phone = textField3.getText();
        String email = textField4.getText();
        String memo = textField5.getText();

        Person person = newPerson(name, birthDate, phone, email, memo);
        return person;
    }

    // 格式校验
    public boolean verify(){
        String name = textField1.getText();
        String birthDate = textField2.getText();
        String email = textField4.getText();

        boolean isBirthDate = Pattern.matches("\\d{4}-\\d{2}-\\d{2}", birthDate);
        boolean isEmail = Pattern.matches("^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$", email);
        if (name != null && isBirthDate && isEmail)
            return true;
        else
            return false;
    }

    //将 Person对象设置到文本框
    public void setInfo(Person p) {
        String[] arr = p.Getter();
        textField1.setText(arr[0]);
        textField2.setText(arr[1]);
        textField3.setText(arr[2]);
        textField4.setText(arr[3]);
        textField5.setText(arr[4]);
    }

    //清空所有文本框
    public void clearAll() {
        textField1.setText("");
        textField2.setText("");
        textField3.setText("");
        textField4.setText("");
        textField5.setText("");
    }

    // 设置模式：浏览0、新建1、修改2
    public void setMode(int mode) {
        if (mode == 0) { // 浏览模式
            Button1.setEnabled(true);
            Button2.setEnabled(true);
            Button3.setEnabled(false);
            Button4.setEnabled(true);
            textField1.setEditable(false);
            textField2.setEditable(false);
            textField3.setEditable(false);
            textField4.setEditable(false);
            textField5.setEditable(false);
        } else if (mode == 1 || mode == 2) { // 增加或修改模式
            Button1.setEnabled(false);
            Button2.setEnabled(false);
            Button3.setEnabled(true);
            Button4.setEnabled(false);
            textField1.setEditable(false);
            textField2.setEditable(true);
            textField3.setEditable(true);
            textField4.setEditable(true);
            textField5.setEditable(true);
            if (mode == 1){
                clearAll();
                textField1.setEditable(true);
            }
        }
    }

    // 构造方法
    public AddressBook() {
        // 加载信息
        Hashtable<String, Person> ht = load(0);

        // 默认（浏览模式）
        setMode(0);

        // 新建（新增模式）
        Button1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                setMode(1);
            }
        });

        // 修改（修改模式）
        Button2.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                setMode(2);
            }
        });

        // 退出
        Button5.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int quit = JOptionPane.showConfirmDialog(JPanel, "确定保存并退出吗？", "退出提示", 0);
                if (quit == 0) {
                    System.exit(0);
                }
            }
        });

        //限制只能选择一个元素
        list1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        // 默认选择第一项
        list1.setSelectedIndex(0);

        // 列表选择监听
        list1.addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) {
                setMode(0);
                String select = (String) list1.getSelectedValue();
                if (select != null)
                    setInfo(ht.get(select));
            }
        });

        // 保存
        Button3.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                boolean v = verify(); // 验证
                if (v){
                    Person person = getInfo();
                    String name = textField1.getText();
                    if(ht.containsKey(name))
                        ht.remove(name);
                    ht.put(name, person);
                    save(ht);
                    load(0);
                    setMode(0);
                } else {
                    JOptionPane.showMessageDialog(JPanel,"信息格式错误！","错误 ",0);
                }
            }
        });

        // 删除
        Button4.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String name = textField1.getText();
                ht.remove(name);
                save(ht);
                load(0);
            }
        });
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("个人信息");
        frame.setContentPane(new AddressBook().JPanel);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setSize(650, 500);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        // 退出事件监听
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                int quit = JOptionPane.showConfirmDialog(frame, "确定保存并退出吗？", "退出提示", 0);
                if (quit == 0) {
                    System.exit(0);
                }
            }
        });

    }
}
